//
//  CropViewController.m
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 4/13/13.
//  Copyright (c) 2013 UIT. All rights reserved.
//

#import "CropViewController.h"
#import "EffectViewController.h"
#import "Utils.h"

#define W_BUTTON_MENU_BAR 48
#define H_BUTTON_MENU_BAR 40

#define SQUARE_CROP_INDEX 0
#define CUSTOM_CROP_INDEX 1

@interface CropViewController (){
    int curActionIndex;
    UIImage* activeBackgroundImage;
}

- (void) tapButton;

@end

@implementation CropViewController

//@synthesize imageRect;
@synthesize isEnableCrop,
delegate,
inputImg,
cropRectInit,
stepRotate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        stepRotate = 0;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    isCoverImage = false;
    isEnableCrop = true;
    self.view.backgroundColor = [UIColor blackColor];
//    [self didChooseImageTap];
}

-(void)loadView{
    [super loadView];
    [self addNewActionBarMenu];

    float padding = 0;
    cropView = [[CropView alloc] initWithFrame:CGRectMake(padding, padding, self.view.frame.size.width - 2*padding, self.view.frame.size.height - actionBarMenu.frame.size.height - 2*padding) padding:24 cropRatio:-1 topBottomArrowImage:[UIImage imageNamed:@"crop_arrow.png"] leftRightArrowImage:[UIImage imageNamed:@"crop_arrow.png"] arrowSize:50];
    cropView.minCropSize = CGSizeMake(120, 120);
    cropView.delegate = self;
    cropView.isEnableCrop = true;
    if(inputImg){
        if(cropRectInit.size.width != 0 && cropRectInit.size.height != 0)
           [self inputImage:inputImg cropFrame:cropRectInit step:stepRotate];
       else [self inputImage:inputImg];
    }
    [self.view addSubview:cropView];
    
    activeBackgroundImage = [[UIImage imageNamed:@"active_background.png"] retain];
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(0, 0, 20, 10);
    [button addTarget:self action:@selector(didChooseImageTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(void)dealloc{
    [activeBackgroundImage release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)addNewActionBarMenu
{
    int menuBarHeight = 46;
    CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
    UIImage* imageBackground = [UIImage imageNamed: @"bar1.png"];
    
    NSArray *imageNormal = nil;
    imageNormal = [[[NSArray alloc] initWithObjects:
                   [UIImage imageNamed:@"icon-catvuong.png"],
                   [UIImage imageNamed:@"icon-cattoanmanghinh.png"],
                   nil] autorelease];
    
    int numButton = 0;
    if(isCoverImage == false) numButton = imageNormal.count;
    
    actionBarMenu = [[ImageActionBarView alloc] initWithKindButton:numButton
                                                       spaceButton:0
                                                       imageNormal:imageNormal
                                                    imagesSelected:nil
                                                        sizeButton:CGSizeMake(W_BUTTON_MENU_BAR, H_BUTTON_MENU_BAR)
                                                             frame:CGRectMake(0,screenFrame.size.height - menuBarHeight, screenFrame.size.width, menuBarHeight)
                                                   imageBackground:imageBackground
                                                          delegate:self];
    
    
    
    [self.view addSubview:actionBarMenu];
    
    [actionBarMenu release];
}

-(void)inputImage:(UIImage*)image{
    [cropView setImage:image];
    [cropView updateView];
}

-(void)inputImage:(UIImage*)image cropFrame:(CGRect)rect step:(int)step{
    [cropView setImage:image];
    [cropView setNormalizeCropRect:rect withStep:step];
}


-(void)didChooseImageTap{
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:imagePicker animated:YES];
    [imagePicker release];
}

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo{
    
    [self inputImage:image];
    [imagePicker dismissModalViewControllerAnimated:YES];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [imagePicker dismissModalViewControllerAnimated:YES];
}

- (void)finishedActionSelected:(id)sender indexSelect:(int)iIndexSelected{
    curActionIndex = iIndexSelected - 2;
    switch (iIndexSelected) {
        case kTagLeft:
            if(delegate && [delegate respondsToSelector:@selector(didCropResultImage:cropRect:sender:)])
                [delegate didCropResultImage:nil cropRect:CGRectMake(0, 0, 0, 0) sender:self];
            [self dismissModalViewControllerAnimated:YES];
            break;
        case kTagRight:
            if(delegate && [delegate respondsToSelector:@selector(didCropResultImage:cropRect:sender:)])
                [delegate didCropResultImage:[self outputImage] cropRect:[cropView getNormalizeCropRect] sender:self];
            [self dismissModalViewControllerAnimated:YES];
            break;
        case 2:
            cropView.isEnableCrop = true;
            cropView.ratio = 1;
            [actionBarMenu updateBackgroundImageButtonAtIndex:SQUARE_CROP_INDEX imageButton:activeBackgroundImage];
            [actionBarMenu updateBackgroundImageButtonAtIndex:CUSTOM_CROP_INDEX imageButton:nil];
            [cropView updateView];
            break;
        case 3:
            cropView.isEnableCrop = true;
            cropView.ratio = -1;
            [actionBarMenu updateBackgroundImageButtonAtIndex:SQUARE_CROP_INDEX imageButton:nil];
            [actionBarMenu updateBackgroundImageButtonAtIndex:CUSTOM_CROP_INDEX imageButton:activeBackgroundImage];
            [cropView updateView];
            break;
    }
    
}



-(UIImage*)outputImage{
    CGRect cropRect = cropView.cropRect;
    CGRect imageRect = cropView.imageRect;
    float scale = cropView.scale;
    CGRect cropRectImage = CGRectMake((cropRect.origin.x - imageRect.origin.x)/scale,
                                 (cropRect.origin.y - imageRect.origin.y)/scale,
                                 cropRect.size.width/scale, cropRect.size.height/scale);
    CGImageRef newImageRef = CGImageCreateWithImageInRect([cropView.image CGImage], cropRectImage);
    UIImage* cropImage = [UIImage imageWithCGImage:newImageRef];
    CGImageRelease(newImageRef);
    return cropImage;
}

- (void)cropViewDidChangeCropSize:(CropView *)cropView isFullImage:(bool)isFull{
    if(curActionIndex == CUSTOM_CROP_INDEX){
        if(isFull)
            [actionBarMenu updateBackgroundImageButtonAtIndex:CUSTOM_CROP_INDEX imageButton:activeBackgroundImage];
        else [actionBarMenu updateBackgroundImageButtonAtIndex:CUSTOM_CROP_INDEX imageButton:nil];
    }
}
@end
